NPOI

您所在的位置:网站首页 npoi datatable NPOI

NPOI

#NPOI| 来源: 网络整理| 查看: 265

Read and Write Excel files in C# .NET Core using NPOI Read write excel in dotnet core 22 npoi

Today in this article we shall see how to use NPOI to perform Read and Write Excel files in C#.NET Core. In our last post, we saw the usage of OpenXML SDK (open-source SDK from Microsoft) to work with Office Word, Excel, and PowerPoint. We also looked at another easy-to-use library called EPPlus too.

Today, in this article we shall cover below using NPOI,

You don’t need Microsoft OfficeGetting StartedRead the content of the excel file using NPOIExport/Write the data to an Excel file using NPOISummary

Please see the below references if interested to know more about them.

Read/Write Excel file .NET Core using OpemXML SDK Read/Write Excel file in .NET Core using EPPlus

We shall be looking into one more simple approach of dealing with office excel using the NPOI .NET Core Library.

You don’t need Microsoft Office

Please note that Read and Creating Excel in C# is possible without installing Microsoft Office. Today we will see a possible and easy-to-implement approach.

Getting Started

Let’s create a .NET Core project, you can choose any project template. Here we shall use the .NET Core 3.1 or .NET 5 Console project.

excel read write npoi dot net core consoleproject

NuGet’s package name is NPOI. Let’s install this package,

PM> Install-Package NPOI -Version 2.5.1

OR

Please install from Nuget manager,

excel read write npoi

Note: Please use the latest available version

Let’s look at a simple Excel file with the below column and row details. Let’s try to read the file using our NPOI API,

Read excel in dotnet core 21

Read the content of the excel file using NPOI

POC example as below. This ready to use API can be used in .NET Core console, or Test project or ASP.NET Core application or logic can be modified or improved as per your requirements.

static string ReadExcel() { DataTable dtTable = new DataTable(); List rowList = new List(); ISheet sheet; using (var stream = new FileStream("TestData.xlsx", FileMode.Open)) { stream.Position = 0; XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream); sheet = xssWorkbook.GetSheetAt(0); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue; { dtTable.Columns.Add(cell.ToString()); } } for (int i = (sheet.FirstRowNum + 1); i d.CellType == CellType.Blank)) continue; for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString())) { rowList.Add(row.GetCell(j).ToString()); } } } if(rowList.Count>0) dtTable.Rows.Add(rowList.ToArray()); rowList.Clear(); } } return JsonConvert.SerializeObject(dtTable); }

After executing the above API, one can easily read all the Excel details.

In the above example, I have used the file “testdata.xlsx” as input. I have kept this file in the output directory bin\Debug\netcoreapp2.1. Also if needed you can keep the file locally like ex. string strDoc = @”C:\Users\Public\Documents\testdata .xlsx” .

I am showing the results as JSON out as shown below,

One can map the above output details to respective class objects using the mapping logic of their choice.

Export/Write the data to an Excel file using NPOI

We shall now look at creating or writing the data into an Excel file.

Here is sample data/object which we want to save as an Excel file.

image

I am creating a new Excel file in the same project folder to keep everything simple. (Excel file will get created in the ‘bin’ folder of the project). The complete sample API is as below.

static void WriteExcel() { List persons = new List() { new UserDetails() {ID="1001", Name="ABCD", City ="City1", Country="USA"}, new UserDetails() {ID="1002", Name="PQRS", City ="City2", Country="INDIA"}, new UserDetails() {ID="1003", Name="XYZZ", City ="City3", Country="CHINA"}, new UserDetails() {ID="1004", Name="LMNO", City ="City4", Country="UK"}, }; // Lets converts our object data to Datatable for a simplified logic. // Datatable is most easy way to deal with complex datatypes for easy reading and formatting. DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable))); var memoryStream = new MemoryStream(); using (var fs = new FileStream("Result.xlsx", FileMode.Create, FileAccess.Write)) { IWorkbook workbook = new XSSFWorkbook(); ISheet excelSheet = workbook.CreateSheet("Sheet1"); List columns = new List(); IRow row = excelSheet.CreateRow(0); int columnIndex = 0; foreach (System.Data.DataColumn column in table.Columns) { columns.Add(column.ColumnName); row.CreateCell(columnIndex).SetCellValue(column.ColumnName); columnIndex++; } int rowIndex = 1; foreach (DataRow dsrow in table.Rows) { row = excelSheet.CreateRow(rowIndex); int cellIndex = 0; foreach (String col in columns) { row.CreateCell(cellIndex).SetCellValue(dsrow[col].ToString()); cellIndex++; } rowIndex++; } workbook.Write(fs); } }

Once you execute ‘workbook.Write(fs)‘ will save the file to the ‘bin’ folder location. You can modify the location of the generated file as needed.

After executing the above API, a new Excel file will be created with the above custom objects transformed into respective Excel Columns and Rows details as below,

excel read write npoi dot net core file

That’s all, we just learned how to import and export data to/from excel in a simple way in .NET Core framework-based application using the NPOI library.

Please visit the GitHub link for the complete code.

Other References :

Read/Write Excel file .NET Core using OpemXML SDK Read/Write Excel file in .NET Core using EPPlus

Are you dealing with any complex scenarios? Please let me know and sound off your comments below!

Summary

The NPOI library provides us with easy control while dealing with the Office Excel file. Today we learned, how to import and export data to/from excel in the .NET Core framework using the NPOI library.

The legacy so-called applications like Excel or word are no more legacy and can be used on any platform using simple libraries like NPOI etc.

References:

Export SQL Table To Excel using NPOIHow to Read Web.Config Configuration .NET CoreHow to Write Byte array to File C# examplesUpload Files in Swagger UI OpenAPI ASP.NET CoreCsvHelper – Read CSV files in C# .NET Core

Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published best practices and guidelines for software design and development.

Growing by Sharing

You might be interested :C# Read CSV file in .NET Core -TextFieldParserEPPlus - Read/Write Excel files in .NET Core using C#Read files Google Cloud Storage using Python


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3